import type { Router, RouteRecordRaw } from 'vue-router'

import { isObject, hasOwn } from '@/utils'
import { useStore } from '@/store'

import { appConfig, configSetting } from '@/config'

/*
 *  权限控制
 */
export const checkAuth = (key: string) => {
  const userStore = useStore().useUserStore
  return true
  return !!userStore().permissionAuth(key)
}

/*
 *  路由 文件加载
 */
export const loadesFiles = (files: Record<string, any>) =>
  Object.keys(files)
    .reduce((arr: any, key: any) => {
      if (typeof files[key].default === 'object') {
        return arr.concat(files[key].default)
      }
      return arr
    }, [])
    .sort((prev: any, next: any) => (prev?.meta?.sort || 0) - next?.meta?.sort)

/*
 *   路由层级提升
 */

export const routesUpgradeLevels = (routes: RouteRecordRaw[]) => {
  return routes.map((route: RouteRecordRaw) => {
    if (Array.isArray(route.children) && route.children.length === 1) {
      return {
        meta: route.meta,
        ...route.children[0]
      }
    }
    return route
  })
}

/*
 *   扁平化
 */
export function getFlatMenuList(menuList: any) {
  const newMenuList = JSON.parse(JSON.stringify(menuList))
  return newMenuList.flatMap((item: any) => [
    item,
    ...(item.children ? getFlatMenuList(item.children) : [])
  ])
}

// 处理tree权限丢失父级id
// # 新增用户时给角色权限， 处理缺失id
// # origin： 权限数组  arr： 选中的权限id数组
export function setPermissionIds(origin: any = [], arr: any = []) {
  const _arr: any = []
  function delIds(array: any) {
    array.forEach((item: any) => {
      if (!item.children && arr.includes(item.id)) {
        _arr.push(item.id)
      }
      if (item.children) {
        delIds(item.children)
      }
    })
  }
  delIds(origin)
  return _arr
}

// # 角色回显数据时，去除丢失的id
// # origin： 权限原数组  arr： 选中的权限id数组
export function getPermissionIds(origin: any = [], arr: any = []) {
  const _ids: any = {}
  arr.forEach((id: any) => (_ids[id] = true))
  function setId(item: any) {
    if (_ids[item.id]) {
      return true
    }
    let flag = false
    if (Array.isArray(item.children)) {
      for (const child of item.children) {
        if (setId(child)) {
          _ids[item.id] = true
          flag = true
        }
      }
    }
    return flag
  }
  origin.forEach((item: any) => setId(item))
  return Object.keys(_ids)
}

/*
    获取 路径 参数
*/
export function getTokenByUrl(url: string) {
  const strs = url.split('?')[1]
  const paramt = strs.split('&')
  const obj: any = {}
  for (let i = 0; i < paramt.length; i++) {
    const g = paramt[i].split('=')
    obj[g[0]] = g[1]
  }
  return obj
}

export function getVal(form: any, s: string): any {
  if (!isObject(form)) {
    return
  }
  return s
    .replace(/\[(\w+)\]/g, '.$1')
    .replace(/^\./, '')
    .split('.')
    .reduce((prev: object | undefined | any, cur) => {
      if (prev && hasOwn(prev, cur)) {
        return prev[cur]
      }
    }, form)
}

export const getFullYears = (val: number) => {
  // 获取指定年份开始到现在年份的数组
  // 获取到从那一年开始
  // val == 指定年份
  const classOption = []
  let NowYears = new Date().getFullYear() // 获取当前年
  const Years = NowYears - val // 获取当前年和指定年份的插值
  for (let index = 0; index <= Years; index++) {
    classOption.push({ label: NowYears-- + '年', value: NowYears + 1 })
  }
  return classOption
}

export const getAllYear = (yearNumber: number) => {
  // 年份 的 前几年 与 后几年
  const years = []
  const y = new Date().getFullYear()
  for (let i = 0; i <= yearNumber; i++) {
    if (i < yearNumber) {
      years.unshift({ value: y - i, label: y - i + '年' })
    } else {
      for (let x = 1; x < yearNumber; x++) {
        years.push({ value: y + x, label: y + x + '年' })
      }
    }
  }
  return years
}

export const setBaseUrlFile = (str: string) => {
  return str.replaceAll(
    /(!\[.*\]\(|<img src=")(?!http)/g,
    `$1${appConfig.baseApiUrl}`
  )
}

export const removeBaseUrlFile = (str: string) => {
  return str.replaceAll(appConfig.baseFilesUrl, '')
}

export const goKanban = (router: Router) => {
  router.push({
    name: configSetting.KanBanName
  })
}

export const back = (router: Router) => {
  router.back()
}

export function formateTimeStamp(time: number) {
  const date = new Date(time)
  const year = date.getFullYear()
  const month =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

  return year + '/' + month + '/' + day
}

export function getNowTime(id: string) {
  const time = new Date()
  //获取时分秒
  let h = time.getHours()
  let m = time.getMinutes()
  let s = time.getSeconds()

  //检查是否小于10
  h = check(h)
  m = check(m)
  s = check(s)
  // document.getElementById('nowtime').innerHTML = h + ':' + m + ':' + s;
  const eleMent = document.getElementById(id)
  if (eleMent) {
    eleMent.innerHTML = h + ':' + m + ':' + s
  }
}

export function check(i: number) {
  // 方法二，if语句判断
  if (Number(i) < 10) {
    i = Number('0' + i)
  }
  return i
}

export const getMap = (map: Map<string, any>) => {
  const result: string[] = []
  for (const [key, value] of map.entries()) {
    result.push(value)
  }
  return result
}
